package util.jackson.serializer;

import com.fasterxml.jackson.databind.ObjectMapper;
import shared.model.ExtensionPoint;

import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

/**
 * @author Gregory Boissinot
 */
public class ImplementationMapper {

    private static ImplementationMapper INSTANCE;

    private final ObjectMapper objectMapper;
    private final Map<String, Class<? extends ExtensionPoint>> deserializerClassMapper;

    private ImplementationMapper() {
        this.objectMapper = new ObjectMapper();
        this.deserializerClassMapper = new HashMap();
        this.objectMapper.registerModule(new DiscoverableSubtypeValueObjectModule());

        //-- ExtensionPoint
        ServiceLoader<ExtensionPoint> serviceLoader1 = ServiceLoader.load(ExtensionPoint.class);
        serviceLoader1.reload();
        for (ExtensionPoint extensionPoint : serviceLoader1) {
            deserializerClassMapper.put(extensionPoint.getName(), extensionPoint.getClass());
        }
    }

    public static ObjectMapper getObjectMapper() {
        return getInstance().objectMapper;
    }

    private static ImplementationMapper getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new ImplementationMapper();
        }
        return INSTANCE;
    }

    public static Map<String, Class<? extends ExtensionPoint>> getDeserializerClassMapper() {
        return getInstance().deserializerClassMapper;
    }
}
